import { fetchListData } from './model';
import StudentList from './components/StudentList';
import TeacherList from './components/TeacherList';

class App extends React.Component {
  state = {
    studentList: [],
    teacherList: []
  };

  //当组件挂载完毕时
  async componentDidMount() {
    const studentData = await fetchListData('student');
    /**
     * console.log('student',res.data);
     * [
     *   {id: 1, name: '小红', grade: 1},
     *   {id: 2, name: '小明', grade: 2},
     *   {id: 3, name: '小王', grade: 3}
     * ]
     */
    const teacherData = await fetchListData('teacher');
    /**
     * console.log('teacher', res.data);
     * [
     *   {id: 1, name: 'stefen', subject: 'English', like: 0},
     *   {id: 2, name: 'lucy', subject: 'Maths', like: 0},
     *   {id: 3, name: 'icey', subject: 'Sports', like: 0}
     * ]
     */

    //将请求的数据保存到state里
    this.setState({
      studentList: studentData.data,
      teacherList: teacherData.data
    });
  }

  removeStudent(id) {
    this.setState({
      studentList: this.state.studentList.filter((item) => item.id !== id)
    });
  }

  likeTeacher(id) {
    this.setState({
      teacherList: this.state.teacherList.map((item) => {
        if (item.id === id) {
          item.like += 1;
        }
        return item;
      })
    });
  }

  render() {
    return (
      // 给子组件绑定数据和方法
      <div className="app">
        <StudentList
          data={this.state.studentList}
          removeStudent={this.removeStudent.bind(this)}
        ></StudentList>
        <hr />
        <TeacherList
          data={this.state.teacherList}
          likeTeacher={this.likeTeacher.bind(this)}
        ></TeacherList>
      </div>
    );
  }
}

export default App;
